package com.example.service

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.service.MainActivity.Companion.TAG
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.Socket
import kotlin.math.log

class MainActivity : AppCompatActivity() {
    companion object {
        const val TAG = "Socket"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        CoroutineScope(Dispatchers.IO).launch {
            val socket = withContext(Dispatchers.IO) {
                try {
                    Socket("192.168.22.183", 21).apply { soTimeout = 10000 }
                } catch (e: Exception) {
                    e.printStackTrace()
                    null
                }
            }
            if (socket == null || !socket.isConnected) {
                return@launch
            }
            Log.d(TAG, "isConnected: ${socket.isConnected}")
            val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
            val writer = OutputStreamWriter(socket.getOutputStream())
            sendCommand(writer, reader, "SYST")
            sendCommand(writer, reader, "USER liangyuyini")
            sendCommand(writer, reader, "PASS qwe")
            sendCommand(writer, reader, "PASV")
        }
    }
}

fun sendCommand(
    writer: OutputStreamWriter,
    reader: BufferedReader,
    command: String,
): String {
    writer.write(command + "\r\n")
    writer.flush()
    var line: String
    val sb = StringBuilder()

    while (reader.readLine().also { line = it } != null && !line.endsWith("-1")) {
        sb.append("$line\n")
    }
    val res = sb.toString()
    Log.d(TAG, "sendCommand: $res")
    return res
}